package handlers

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"novel-mgmt/cache"
	"novel-mgmt/models"
	"strconv"
	"time"
)

func List(c *gin.Context) {
	var nov []models.Nov

	redis_key := "list_nov"
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Find(&nov)
		jsonData, _ := json.Marshal(nov)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &nov)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": nov,
	})
	return
}
func Detail(c *gin.Context) {
	id := c.Query("id")
	var nov models.Nov
	redis_key := "detail_nov" + id
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Where("id = ?", id).First(&nov)
		jsonData, _ := json.Marshal(nov)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &nov)
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": nov,
	})
	return
}
func Comment(c *gin.Context) {
	userId, _ := strconv.Atoi(c.PostForm("user_id"))
	novId, _ := strconv.Atoi(c.PostForm("nov_id"))
	content := c.PostForm("content")

	if content == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不为空",
		})
		return
	}

	comment := models.Comment{
		Content: content,
		UserID:  userId,
		NovID:   novId,
	}
	err := models.DB.Create(&comment).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "评论添加失败",
		})
		return
	}

	var nov models.Nov
	err = models.DB.Where("id= ?", novId).First(&nov).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "数据不存在",
		})
		return
	}

	nov.CommentCount++
	err = models.DB.Save(&nov).Order("id desc").Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "评论失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "评论成功",
	})
	return

}
